package com.quanyan.ic.datacenter.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * Created by Administrator on 2017/8/24.
 */
@Configuration
@MapperScan(basePackages = {"com.quanyan.ic.datacenter.mapper.icData"},sqlSessionFactoryRef = "sqlSessionFactoryBeanIc")
public class DataCenterDSConfig {

    @Bean(name = "icDataSource", destroyMethod = "close", initMethod = "init")
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSource icDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "sqlSessionFactoryBeanIc")
    @Primary
    public SqlSessionFactory sqlSessionFactoryBeanIc() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(icDataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/com/quanyan/ic/datacenter/mapper/icData/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    @Primary
    public PlatformTransactionManager placeTransactionManager(@Qualifier("icDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
